import { setStore, getStore, clearStore } from '@/utils/store.ts';
import { handleLogin } from '../../api/home';
import router from '../../router/router';
import { getMenus } from '../../api/menus';
import { defineAsyncComponent } from 'vue';
import { RouteRecordRaw } from 'vue-router';
import {Empty} from 'ant-design-vue';
type ResponseRaw = {
  code: number;
  msg: string;
  data: any;
};
const common = {
  state: {
    user: getStore({ name: 'user' }) || {},
    token: getStore({ name: 'token' }) || '',
    loading: true,
    keyPath: getStore({ name: 'keyPath' }) || [],
    tabs: getStore({ name: 'tabs' }) || [],
    menus: getStore({ name: 'menus' }) || [],
  },
  mutations: {
    set_keypath(state: any, prop: []) {
      state.keyPath = prop;
      setStore({ name: 'keyPath', content: state.keyPath });
    },
    set_user(state: any, content: any) {
      state.user = content;
      setStore({ name: 'user', content });
    },
    set_token(state: any, token: any) {
      state.token = token;
      setStore({ name: 'token', content: token });
    },
    set_loading(state: any, isShow: boolean) {
      state.loading = isShow;
    },
    clear_user(state: any) {
      state.user = {};
      state.token = '';
      state.tabs = [];
    },
    rm_tabs(state: any, tab: any) {
      state.tabs.forEach((item: any, index: number) => {
        if (tab.name === item.name) {
          state.tabs.splice(index, 1);
        }
      });
      setStore({ name: 'tabs', content: state.tabs });
    },
    set_tabs(state: any, tab: any) {
      const paths: string[] = state.tabs.map((r: any) => r.path);
      if (tab.path === '/home') {
        return false;
      }
      if (paths.includes(tab.path)) {
        for (const r of state.tabs) {
          if (r.path === tab.path) {
            r.current = true;
          } else {
            r.current = false;
          }
        }
        setStore({ name: 'tabs', content: state.tabs });
        return;
      }

      state.tabs.push(tab);
      state.tabs.forEach((r: any, index: number) => {
        if (index === state.tabs.length - 1) {
          r.current = true;
        } else {
          r.current = false;
        }
      });
      setStore({ name: 'tabs', content: state.tabs });
    },
    set_menus(state: any, menus: object[]) {
      state.menus = menus;
      // setStore({ name: "menus", content: state.menus })
    },
  },
  actions: {
    GENERATE_ROUTES({ commit }: any): Promise<ResponseRaw> {
      return new Promise((resolve, reject) => {
        getMenus()
          .then((res: ResponseRaw) => {
            commit('set_menus', res.data);
            const _menus = filtersRouters(res.data);
            for (const $route of _menus) {
              router.addRoute('admin', $route);
            }
            router.addRoute({
              path: '/:pathMatch(.*)',
              name: '404',
              component: () => import('../../views/404.vue'),
            });
            console.log(router.getRoutes(), '--------------> 获取所有路由');
            resolve(res);
          })
          .catch((error: Error) => {
            reject(error);
          });
      });
    },
    USER_LOGIN({ commit }: any, params: any) {
      return new Promise((resolve, reject) => {
        handleLogin(params)
          .then((res: ResponseRaw) => {
            commit('set_user', res.data);
            commit('set_token', res.data.token);
            resolve(res);
          })
          .catch((error: Error) => {
            reject(error);
          });
      });
    },
    USER_LOGOUT({ commit }: any, params: any) {
      commit('clear_user');
      commit('set_menus', []);
      window.localStorage.clear();
    },
  },
};

const importModule = (path: string) => {
  console.log('加载路由component ------> :',path)
  // return () => import(/* @vite-ignore */ `../../views/${path}.vue`);
  return defineAsyncComponent(()=>import(`../../views/${path}.vue`))
};
const filtersRouters = (routes: any) => {
  const modules = import.meta.glob('../../views/*/*.vue');
  console.log('=============>',modules)
  return routes.map((r: any) => {
    const { title, icon, path, parentId, name, keepAlive, component } = r;
    return {
      name,
      icon,
      path,
      meta: { name: title, keepAlive },
      component: modules[`../../views${component}.vue`],
    };
  });
};

export default common;
